<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Vue3.0——reactive和ref原理 | Tab</title><meta name="keywords" content="Vue"><meta name="author" content="Tab"><meta name="copyright" content="Tab"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Vue3.0——reactive和ref原理Vue3采用了新的Proxy实现数据拦截，但Proxy还是只能代理一层。对于深层的对象需要递归代理，相比2.0在初始化递归，3.0的运行时递归，大大减少了初始化的递归性能消耗。 Proxy首先简单了解下Proxy，方便后面学习reactive和ref原理。  Proxy 对象用于创建一个对象的代理，从而实现基本操作的拦截和自定义（如属性查找、赋值、枚举、">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue3.0——reactive和ref原理">
<meta property="og:url" content="https://tabxx.github.io/tab.github.io/2021/02/23/vue3-reactive-ref/index.html">
<meta property="og:site_name" content="Tab">
<meta property="og:description" content="Vue3.0——reactive和ref原理Vue3采用了新的Proxy实现数据拦截，但Proxy还是只能代理一层。对于深层的对象需要递归代理，相比2.0在初始化递归，3.0的运行时递归，大大减少了初始化的递归性能消耗。 Proxy首先简单了解下Proxy，方便后面学习reactive和ref原理。  Proxy 对象用于创建一个对象的代理，从而实现基本操作的拦截和自定义（如属性查找、赋值、枚举、">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://tabxx.github.io/tab.github.io/2021/02/23/vue3-reactive-ref/reactive.png">
<meta property="article:published_time" content="2021-02-23T02:44:22.000Z">
<meta property="article:modified_time" content="2021-08-11T11:37:24.947Z">
<meta property="article:author" content="Tab">
<meta property="article:tag" content="Vue">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://tabxx.github.io/tab.github.io/2021/02/23/vue3-reactive-ref/reactive.png"><link rel="shortcut icon" href="/tab.github.io/images/favicon.ico"><link rel="canonical" href="https://tabxx.github.io/tab.github.io/2021/02/23/vue3-reactive-ref/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/tab.github.io/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?050bcda3cb147a8c0de1c17a337c5466";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/tab.github.io/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Vue3.0——reactive和ref原理',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-08-11 19:37:24'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
          const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
          const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
          const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified

          if (t === undefined) {
            if (isLightMode) activateLightMode()
            else if (isDarkMode) activateDarkMode()
            else if (isNotSpecified || hasNoSupport) {
              const now = new Date()
              const hour = now.getHours()
              const isNight = hour <= 6 || hour >= 18
              isNight ? activateDarkMode() : activateLightMode()
            }
            window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
              if (saveToLocal.get('theme') === undefined) {
                e.matches ? activateDarkMode() : activateLightMode()
              }
            })
          } else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    })(window)</script><meta name="generator" content="Hexo 5.1.1"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src= "" data-lazy-src="/tab.github.io/images/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/tab.github.io/archives/"><div class="headline">文章</div><div class="length-num">10</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tab.github.io/tags/"><div class="headline">标签</div><div class="length-num">7</div></a></div></div></div><hr/></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/tab.github.io/2021/02/23/vue3-reactive-ref/reactive.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/tab.github.io/">Tab</a></span><div id="menus"><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Vue3.0——reactive和ref原理</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-02-23T02:44:22.000Z" title="发表于 2021-02-23 10:44:22">2021-02-23</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-08-11T11:37:24.947Z" title="更新于 2021-08-11 19:37:24">2021-08-11</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>10分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Vue3.0——reactive和ref原理"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Vue3-0——reactive和ref原理"><a href="#Vue3-0——reactive和ref原理" class="headerlink" title="Vue3.0——reactive和ref原理"></a>Vue3.0——reactive和ref原理</h1><p>Vue3采用了新的<code>Proxy</code>实现数据拦截，但<code>Proxy</code>还是只能代理一层。对于深层的对象需要递归代理，相比2.0在初始化递归，3.0的运行时递归，大大减少了初始化的递归性能消耗。</p>
<h2 id="Proxy"><a href="#Proxy" class="headerlink" title="Proxy"></a>Proxy</h2><p>首先简单了解下<code>Proxy</code>，方便后面学习<code>reactive</code>和<code>ref</code>原理。</p>
<blockquote>
<p><strong>Proxy</strong> 对象用于创建一个对象的代理，从而实现基本操作的拦截和自定义（如属性查找、赋值、枚举、函数调用等）。</p>
</blockquote>
<p><strong>基础示例：</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> handler = &#123;</span><br><span class="line">    <span class="comment">// 属性读取操作的捕捉器</span></span><br><span class="line">    get: <span class="function"><span class="keyword">function</span> (<span class="params">target, prop</span>) </span>&#123;</span><br><span class="line">    	<span class="built_in">console</span>.log(<span class="string">&#x27;getting key: &#x27;</span> + prop);</span><br><span class="line">        <span class="keyword">return</span> target[prop];</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 属性设置操作的捕捉器</span></span><br><span class="line">    set: <span class="function"><span class="keyword">function</span> (<span class="params">target, prop, value</span>) </span>&#123;</span><br><span class="line">    	<span class="built_in">console</span>.log(<span class="string">&#x27;setting key: &#x27;</span> + prop + <span class="string">&#x27;, value: &#x27;</span> + value);</span><br><span class="line">    	target[prop] = value;</span><br><span class="line">    	<span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> p = <span class="keyword">new</span> <span class="built_in">Proxy</span>(&#123;&#125;, handler);</span><br><span class="line">p.a = <span class="number">1</span>;			<span class="comment">// setting key: a, value: 1</span></span><br><span class="line">p.b = <span class="literal">undefined</span>;	<span class="comment">// setting key: b, value: undefined</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(p.a, p.b);      </span><br><span class="line"><span class="comment">// getting key: a</span></span><br><span class="line"><span class="comment">// getting key: b</span></span><br><span class="line"><span class="comment">// 1, undefined</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;c&#x27;</span> <span class="keyword">in</span> p, p.c); </span><br><span class="line"><span class="comment">// getting key: c</span></span><br><span class="line"><span class="comment">// false, undefined</span></span><br></pre></td></tr></table></figure>

<p><code>Proxy</code>一起的还有另外一位小伙伴<code>Reflect</code>。</p>
<p><code>Reflect</code>对象的方法与<code>Proxy</code>对象的方法一一对应，只要是<code>Proxy</code>对象的方法，就能在<code>Reflect</code>对象上找到对应的方法。这就让Proxy对象可以方便地调用对应的<code>Reflect</code>方法，完成默认行为，作为修改行为的基础。也就是说，不管<code>Proxy</code>怎么修改默认行为，你总可以在<code>Reflect</code>上获取默认行为。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> handler = &#123;</span><br><span class="line">    <span class="comment">// 属性读取操作的捕捉器</span></span><br><span class="line">    get: <span class="function"><span class="keyword">function</span> (<span class="params">target, prop, receiver</span>) </span>&#123;</span><br><span class="line">    	<span class="built_in">console</span>.log(<span class="string">&#x27;getting key: &#x27;</span> + prop);</span><br><span class="line">        <span class="comment">// ---&gt; Relefct.get</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Reflect</span>.get(target, prop, receiver);</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 属性设置操作的捕捉器</span></span><br><span class="line">    set: <span class="function"><span class="keyword">function</span> (<span class="params">target, prop, value, receiver</span>) </span>&#123;</span><br><span class="line">    	<span class="built_in">console</span>.log(<span class="string">&#x27;setting key: &#x27;</span> + prop + <span class="string">&#x27;, value: &#x27;</span> + value);</span><br><span class="line">        <span class="comment">// ---&gt; Relefct.set</span></span><br><span class="line">    	<span class="keyword">return</span> <span class="built_in">Reflect</span>.set(target, prop, value, receiver);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>Proxy API具体用法详见官方文档。<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy">MDN文档传送门</a></p>
<h2 id="为什么要选用Proxy"><a href="#为什么要选用Proxy" class="headerlink" title="为什么要选用Proxy"></a>为什么要选用Proxy</h2><p> Vue3.0 为什么选用<code>Proxy</code>而不是沿用 <code>Object.defineProperty</code>呢？</p>
<p><strong>Proxy 的优势如下:</strong></p>
<ul>
<li>Proxy 可以直接监听对象而非属性；</li>
<li>Proxy 可以直接监听数组的变化；</li>
<li>Proxy 有多达 13 种拦截方法,不限于 apply、ownKeys、deleteProperty、has 等等是 Object.defineProperty 不具备的；</li>
<li>Proxy 返回的是一个新对象,我们可以只操作新的对象达到目的,而 Object.defineProperty 只能遍历对象属性直接修改；</li>
<li>Proxy 作为新标准将受到浏览器厂商重点持续的性能优化，也就是传说中的新标准的性能红利；</li>
</ul>
<p><strong>Object.defineProperty 的优势如下:</strong></p>
<ul>
<li>兼容性好，支持 IE9，而 Proxy 的存在浏览器兼容性问题,而且无法用 polyfill 磨平，因此 Vue 的作者才声明需要等到下个大版本( 3.0 )才能用 Proxy 重写。</li>
</ul>
<p>对于监听数组变化我们可以来做一个对比</p>
<p><strong>Proxy代理数组：</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line"><span class="keyword">let</span> handler = &#123;</span><br><span class="line">	get	(target, prop, receiver) &#123;</span><br><span class="line">		<span class="built_in">console</span>.log(<span class="string">&#x27;getting key: &#x27;</span> + prop);</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">Reflect</span>.get(target, prop, receiver);</span><br><span class="line">	&#125;,</span><br><span class="line">	set (target, prop, value, receiver) &#123;</span><br><span class="line">		<span class="built_in">console</span>.log(<span class="string">&#x27;setting key: &#x27;</span> + prop + <span class="string">&#x27;, value: &#x27;</span> + value);</span><br><span class="line">		<span class="keyword">return</span> <span class="built_in">Reflect</span>.set(target, prop, value, receiver);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> proxyArray = <span class="keyword">new</span> <span class="built_in">Proxy</span>(arr, handler);</span><br><span class="line"></span><br><span class="line">proxyArray.push(<span class="number">4</span>);</span><br><span class="line"><span class="comment">// 往数组push时，length也会随之改变</span></span><br><span class="line"><span class="comment">// getting key: push</span></span><br><span class="line"><span class="comment">// getting key: length</span></span><br><span class="line"><span class="comment">// setting key: 3, value: 4</span></span><br><span class="line"><span class="comment">// setting key: length, value: 4</span></span><br><span class="line">proxyArray[<span class="number">0</span>] = <span class="number">0</span>;</span><br><span class="line"><span class="comment">// setting key: 0, value: 0</span></span><br></pre></td></tr></table></figure>

<p>**Object.defineProperty **代理数组：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> orginalProto = <span class="built_in">Array</span>.prototype;	<span class="comment">// Array原型</span></span><br><span class="line"><span class="keyword">const</span> arrayProto = <span class="built_in">Object</span>.create(orginalProto); <span class="comment">// 复制一份原型用于重写</span></span><br><span class="line"><span class="keyword">const</span> methodsToPatch = [	<span class="comment">// 需要重写的数组内置方法</span></span><br><span class="line">	<span class="string">&#x27;push&#x27;</span>,</span><br><span class="line">	<span class="string">&#x27;pop&#x27;</span>,</span><br><span class="line">	<span class="string">&#x27;shift&#x27;</span>,</span><br><span class="line">	<span class="string">&#x27;unshift&#x27;</span>,</span><br><span class="line">	<span class="string">&#x27;splice&#x27;</span>,</span><br><span class="line">	<span class="string">&#x27;sort&#x27;</span>,</span><br><span class="line">	<span class="string">&#x27;reverse&#x27;</span></span><br><span class="line">];	</span><br><span class="line">methodsToPatch.forEach(<span class="function"><span class="params">method</span> =&gt;</span> &#123;</span><br><span class="line">	arrayProto[method] = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">		<span class="comment">// 执行数组原始方法</span></span><br><span class="line">		orginalProto[method].apply(<span class="built_in">this</span>, <span class="built_in">arguments</span>);</span><br><span class="line">		<span class="comment">// do sth </span></span><br><span class="line">		<span class="built_in">console</span>.log(<span class="string">&#x27;数组改变：&#x27;</span>, method , ...arguments);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;)</span><br><span class="line">		</span><br><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line">arr.__proto__ = arrayProto;	<span class="comment">// 改变__proto__指向</span></span><br><span class="line">arr.push(<span class="number">4</span>);	<span class="comment">// 数组改变： push 4</span></span><br><span class="line">arr[<span class="number">0</span>] = <span class="number">0</span>;		<span class="comment">// 没有输出</span></span><br><span class="line"><span class="built_in">console</span>.log(arr);<span class="comment">// [0, 1, 2, 3, 4];</span></span><br></pre></td></tr></table></figure>

<p>上面两种实现数组代理方式对比，实现上<code>Proxy</code>来的更便捷，且能监听到通过数组下标改变数组值的形式。而<code>Object.defineProperty</code>则是通过重写原型上的方式来监听数组的变化，而且监听不到通过数组下标改变数组值的形式。</p>
<h2 id="reactive-原理"><a href="#reactive-原理" class="headerlink" title="reactive 原理"></a>reactive 原理</h2><p>一些工具函数，后面会一一用到。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 工具方法： 判断是否为对象</span></span><br><span class="line"><span class="keyword">const</span> isObject = <span class="function"><span class="params">val</span> =&gt;</span> val !== <span class="literal">null</span> &amp;&amp; <span class="keyword">typeof</span> val === <span class="string">&#x27;object&#x27;</span>;</span><br><span class="line"><span class="comment">// 工具函数：值是否改变</span></span><br><span class="line"><span class="keyword">const</span> hasChanged = <span class="function">(<span class="params">value, oldValue</span>) =&gt;</span> value !== oldValue &amp;&amp; (value === value &amp;&amp; oldValue === oldValue);</span><br><span class="line"><span class="comment">// 工具方法:判断当前key是否存在</span></span><br><span class="line"><span class="keyword">const</span> hasOwn = <span class="function">(<span class="params">val, key</span>) =&gt;</span> <span class="built_in">Object</span>.hasOwnProperty.call(val, key);</span><br></pre></td></tr></table></figure>

<p>首先我们需要一个<code>reactive</code>方法用来创建响应式数据</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 暴露出去的方法，reactive</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">reactive</span>(<span class="params">target</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> createReactiveObject(target, baseHandlers);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>createReactiveObject</code>方法创建一个Proxy实例</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 基础的处理器对象</span></span><br><span class="line"><span class="keyword">const</span> baseHandlers = &#123;</span><br><span class="line">	get, set</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 创建一个响应式对象</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createReactiveObject</span>(<span class="params">target, baseHandlers</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Proxy</span>(target, baseHandlers);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">&#96;&#96;&#96;javascript</span><br><span class="line">&#x2F;&#x2F; 生成get</span><br><span class="line">function createGetter() &#123;</span><br><span class="line">	return function get(target, key, recevier) &#123;</span><br><span class="line">		const result &#x3D; Reflect.get(target, key, recevier);</span><br><span class="line">		console.log(&#96;getting key: $&#123;key&#125;&#96;);</span><br><span class="line"></span><br><span class="line">    	&#x2F;&#x2F; 深层代理</span><br><span class="line">    	if (isObject(result)) &#123;</span><br><span class="line">    		return reactive(result);</span><br><span class="line">    	&#125;</span><br><span class="line">        return result</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F; 生成set</span><br><span class="line">function createSetter() &#123;</span><br><span class="line">	return function set(target, key, value, recevier) &#123;</span><br><span class="line">		const oldValue &#x3D; target[key];</span><br><span class="line">		const hadKey &#x3D; hasOwn(target, key);</span><br><span class="line">		const result &#x3D; Reflect.set(target, key, value, recevier);</span><br><span class="line"></span><br><span class="line">		if (!hadKey) &#123;</span><br><span class="line">			console.log(&#96;add key：$&#123;key&#125;，value：$&#123;value&#125;&#96;);</span><br><span class="line">            &#x2F;&#x2F; trigger(target, &#39;add&#39; &#x2F;* ADD *&#x2F;, key, value);</span><br><span class="line">		&#125; else if (hasChanged(value, oldValue)) &#123;</span><br><span class="line">			console.log(&#96;set key：$&#123;key&#125;，value：$&#123;value&#125;&#96;);</span><br><span class="line">			&#x2F;&#x2F; trigger(target, &#39;set&#39; &#x2F;* SET *&#x2F;, key, value, oldValue);</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		return result</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">const get &#x3D; createGetter();</span><br><span class="line">const set &#x3D; createSetter();</span><br></pre></td></tr></table></figure>

<p><strong>测试reactive</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> proxyObj = reactive(&#123;</span><br><span class="line">	id: <span class="number">1</span>,</span><br><span class="line">	name: <span class="string">&#x27;tab&#x27;</span>,</span><br><span class="line">	childObj: &#123;</span><br><span class="line">    	age: <span class="number">24</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">proxyObj.name = <span class="string">&#x27;xxTab&#x27;</span>;	</span><br><span class="line"><span class="comment">// set key：name，value：xxTab</span></span><br><span class="line">proxyObj.childObj.age = <span class="number">2</span>;</span><br><span class="line"><span class="comment">// getting key: childObj</span></span><br><span class="line"><span class="comment">// set key：age，value：2</span></span><br></pre></td></tr></table></figure>

<p><strong>总结reactive`原理:</strong></p>
<p><code>reactive</code>本质上就是一个<code>Proxy</code>实例，无非就是在<code>set</code>和<code>get</code>拦截器上加了一些自身的逻辑。比如<code>get</code>拦截器收集依赖，<code>set</code>拦截器触发相关依赖。</p>
<h2 id="ref-原理"><a href="#ref-原理" class="headerlink" title="ref 原理"></a>ref 原理</h2><p>还是一样需要一个暴露出来的<code>ref</code>方法.</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createRef</span>(<span class="params">rawValue, shallow = false</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">new</span> RefImpl(rawValue, shallow)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ref</span>(<span class="params">value</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> createRef(value)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>RefImpl</code>核心类，实现ref的初始化，以及相应的get和set</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RefImpl</span> </span>&#123;</span><br><span class="line">	<span class="keyword">constructor</span>(_rawValue, _shallow = false) &#123;</span><br><span class="line">		<span class="built_in">this</span>._rawValue = _rawValue;</span><br><span class="line">		<span class="built_in">this</span>._shallow = _shallow;</span><br><span class="line">        <span class="built_in">this</span>.__v_isRef = <span class="literal">true</span>;</span><br><span class="line">		<span class="built_in">this</span>._value = _shallow ? _rawValue : convert(_rawValue);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">get</span> <span class="title">value</span>() &#123;</span><br><span class="line">    	<span class="comment">// track(toRaw(this), &#x27;get&#x27; /* GET */, &#x27;value&#x27;);</span></span><br><span class="line">    	<span class="keyword">return</span> <span class="built_in">this</span>._value;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">set</span> <span class="title">value</span>(<span class="params">newVal</span>) &#123;</span><br><span class="line">    	<span class="keyword">if</span> (hasChanged(toRaw(newVal), <span class="built_in">this</span>._rawValue)) &#123;</span><br><span class="line">        	<span class="built_in">this</span>._rawValue = newVal;</span><br><span class="line">        	<span class="built_in">this</span>._value = <span class="built_in">this</span>._shallow ? newVal : convert(newVal);</span><br><span class="line">        	<span class="comment">// trigger(toRaw(this), &#x27;set&#x27; /* SET */, &#x27;value&#x27;, newVal);</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>工具方法</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 工具方法：判断传入的值是否是一个对象，是的话就用 reactive 来代理</span></span><br><span class="line"><span class="keyword">const</span> convert = <span class="function"><span class="params">val</span> =&gt;</span> (isObject(val) ? reactive(val) : val);</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">toRaw</span>(<span class="params">observed</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> (observed &amp;&amp; toRaw(observed[<span class="string">&#x27;__v_raw&#x27;</span>])) || observed</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>测试ref</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> num = ref(<span class="number">1</span>)</span><br><span class="line">num.value = <span class="number">10</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> data = ref([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>])</span><br><span class="line">data.value.push(<span class="number">4</span>)</span><br><span class="line"><span class="built_in">console</span>.log(data.value[<span class="number">3</span>])</span><br></pre></td></tr></table></figure>

<p><strong>总结<code>ref</code>原理:</strong></p>
<p>核心类 <code>RefImpl</code> ，我们可以看到在类中使用了经典的 <code>get/set</code> 存取器，来进行追踪和触发。<br><code>convert</code> 方法让我们知道了 ref 不仅仅用来包装一个值类型，也可以是一个对象/数组，然后把对象/数组再交给 <code>reactive</code> 进行代理。</p>
<h2 id="完整代码"><a href="#完整代码" class="headerlink" title="完整代码"></a>完整代码</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 工具方法： 判断是否为对象</span></span><br><span class="line"><span class="keyword">const</span> isObject = <span class="function"><span class="params">val</span> =&gt;</span> val !== <span class="literal">null</span> &amp;&amp; <span class="keyword">typeof</span> val === <span class="string">&#x27;object&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 工具函数：值是否改变</span></span><br><span class="line"><span class="keyword">const</span> hasChanged = <span class="function">(<span class="params">value, oldValue</span>) =&gt;</span> value !== oldValue &amp;&amp; (value === value &amp;&amp; oldValue === oldValue);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 工具方法:判断当前key是否存在</span></span><br><span class="line"><span class="keyword">const</span> hasOwn = <span class="function">(<span class="params">val, key</span>) =&gt;</span> <span class="built_in">Object</span>.hasOwnProperty.call(val, key);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 生成get</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createGetter</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">get</span> (<span class="params">target, key, recevier</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">const</span> result = <span class="built_in">Reflect</span>.get(target, key, recevier);</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`getting key: <span class="subst">$&#123;key&#125;</span>`</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 深层代理</span></span><br><span class="line">        <span class="keyword">if</span> (isObject(result)) &#123;</span><br><span class="line">            <span class="keyword">return</span> reactive(result);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> result</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createSetter</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">set</span> (<span class="params">target, key, value, recevier</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">const</span> oldValue = target[key];</span><br><span class="line">        <span class="keyword">const</span> hadKey = hasOwn(target, key);</span><br><span class="line">        <span class="keyword">const</span> result = <span class="built_in">Reflect</span>.set(target, key, value, recevier);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (!hadKey) &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">`add key：<span class="subst">$&#123;key&#125;</span>，value：<span class="subst">$&#123;value&#125;</span>`</span>);</span><br><span class="line">            <span class="comment">// trigger(target, &#x27;add&#x27; /* ADD */, key, value);</span></span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (hasChanged(value, oldValue)) &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">`set key：<span class="subst">$&#123;key&#125;</span>，value：<span class="subst">$&#123;value&#125;</span>`</span>);</span><br><span class="line">            <span class="comment">// trigger(target, &#x27;set&#x27; /* SET */, key, value, oldValue);</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> result</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> get = createGetter();</span><br><span class="line"><span class="keyword">const</span> set = createSetter();</span><br><span class="line"><span class="comment">// 基础的处理器对象</span></span><br><span class="line"><span class="keyword">const</span> baseHandlers = &#123;</span><br><span class="line">    get, set</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 创建一个响应式对象</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createReactiveObject</span> (<span class="params">target, baseHandlers</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Proxy</span>(target, baseHandlers);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 暴露出去的方法，reactive</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">reactive</span> (<span class="params">target</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> createReactiveObject(target, baseHandlers);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// test</span></span><br><span class="line"><span class="keyword">const</span> proxyObj = reactive(&#123;</span><br><span class="line">    id: <span class="number">1</span>,</span><br><span class="line">    name: <span class="string">&#x27;tab&#x27;</span>,</span><br><span class="line">    childObj: &#123;</span><br><span class="line">        age: <span class="number">24</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">proxyObj.name = <span class="string">&#x27;xxTab&#x27;</span>;</span><br><span class="line">proxyObj.childObj.age = <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 工具方法：判断传入的值是否是一个对象，是的话就用 reactive 来代理</span></span><br><span class="line"><span class="keyword">const</span> convert = <span class="function"><span class="params">val</span> =&gt;</span> (isObject(val) ? reactive(val) : val);</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">toRaw</span> (<span class="params">observed</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> (observed &amp;&amp; toRaw(observed[<span class="string">&#x27;__v_raw&#x27;</span>])) || observed</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RefImpl</span> </span>&#123;</span><br><span class="line">    <span class="keyword">constructor</span>(_rawValue, _shallow = false) &#123;</span><br><span class="line">        <span class="built_in">this</span>._rawValue = _rawValue;</span><br><span class="line">        <span class="built_in">this</span>._shallow = _shallow;</span><br><span class="line">        <span class="built_in">this</span>.__v_isRef = <span class="literal">true</span>;</span><br><span class="line">        <span class="built_in">this</span>._value = _shallow ? _rawValue : convert(_rawValue);</span><br><span class="line">    &#125;</span><br><span class="line">    get value () &#123;</span><br><span class="line">        <span class="comment">// track(toRaw(this), &#x27;get&#x27; /* GET */, &#x27;value&#x27;);</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>._value;</span><br><span class="line">    &#125;</span><br><span class="line">    set value (newVal) &#123;</span><br><span class="line">        <span class="keyword">if</span> (hasChanged(toRaw(newVal), <span class="built_in">this</span>._rawValue)) &#123;</span><br><span class="line">            <span class="built_in">this</span>._rawValue = newVal;</span><br><span class="line">            <span class="built_in">this</span>._value = <span class="built_in">this</span>._shallow ? newVal : convert(newVal);</span><br><span class="line">            <span class="comment">// trigger(toRaw(this), &#x27;set&#x27; /* SET */, &#x27;value&#x27;, newVal);</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createRef</span> (<span class="params">rawValue, shallow = false</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> RefImpl(rawValue, shallow)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ref</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> createRef(value)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">shallowRef</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> createRef(value, <span class="literal">true</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * ref test</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">// let num = ref(1)</span></span><br><span class="line"><span class="comment">// num.value = 10;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// let data = ref([1, 2, 3])</span></span><br><span class="line"><span class="comment">// data.value.push(4)</span></span><br><span class="line"><span class="comment">// console.log(data.value[3])</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isRef</span> (<span class="params">r</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">Boolean</span>(r &amp;&amp; r.__v_isRef === <span class="literal">true</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">unRef</span> (<span class="params">ref</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> isRef(ref) ? ref.value : ref;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>







</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Tab</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://tabxx.github.io/tab.github.io/2021/02/23/vue3-reactive-ref/">https://tabxx.github.io/tab.github.io/2021/02/23/vue3-reactive-ref/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://tabxx.github.io/tab.github.io" target="_blank">Tab</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tab.github.io/tags/Vue/">Vue</a></div><div class="post_share"><div class="social-share" data-image="/tab.github.io/2021/02/23/vue3-reactive-ref/reactive.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/tab.github.io/2021/05/15/inject/"><img class="prev-cover" src= "" data-lazy-src="/tab.github.io/2021/05/15/inject/top.jpg" onerror="onerror=null;src='/tab.github.io/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Vue3.0——Provide/Inject的妙用</div></div></a></div><div class="next-post pull-right"><a href="/tab.github.io/2020/03/18/css_var/"><img class="next-cover" src= "" data-lazy-src="/tab.github.io/2020/03/18/css_var/topbg.jpg" onerror="onerror=null;src='/tab.github.io/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">css变量那些事</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/tab.github.io/2019/11/18/computed/" title="computed 实现原理"><img class="cover" src= "" data-lazy-src="/tab.github.io/2019/11/18/computed/topbg.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-18</div><div class="title">computed 实现原理</div></div></a></div><div><a href="/tab.github.io/2021/05/15/inject/" title="Vue3.0——Provide/Inject的妙用"><img class="cover" src= "" data-lazy-src="/tab.github.io/2021/05/15/inject/top.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-05-15</div><div class="title">Vue3.0——Provide/Inject的妙用</div></div></a></div><div><a href="/tab.github.io/2019/11/11/vue-directive/" title="vue自定义指令的魅力"><img class="cover" src= "" data-lazy-src="/tab.github.io/2019/11/11/vue-directive/2701794-250949a6bda06b20.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-11-11</div><div class="title">vue自定义指令的魅力</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src= "" data-lazy-src="/tab.github.io/images/avatar.jpg" onerror="this.onerror=null;this.src='/tab.github.io/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">Tab</div><div class="author-info__description">Tab</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/tab.github.io/archives/"><div class="headline">文章</div><div class="length-num">10</div></a></div><div class="card-info-data-item is-center"><a href="/tab.github.io/tags/"><div class="headline">标签</div><div class="length-num">7</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/Tabxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Vue3-0%E2%80%94%E2%80%94reactive%E5%92%8Cref%E5%8E%9F%E7%90%86"><span class="toc-number">1.</span> <span class="toc-text">Vue3.0——reactive和ref原理</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Proxy"><span class="toc-number">1.1.</span> <span class="toc-text">Proxy</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E9%80%89%E7%94%A8Proxy"><span class="toc-number">1.2.</span> <span class="toc-text">为什么要选用Proxy</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#reactive-%E5%8E%9F%E7%90%86"><span class="toc-number">1.3.</span> <span class="toc-text">reactive 原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ref-%E5%8E%9F%E7%90%86"><span class="toc-number">1.4.</span> <span class="toc-text">ref 原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%8C%E6%95%B4%E4%BB%A3%E7%A0%81"><span class="toc-number">1.5.</span> <span class="toc-text">完整代码</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/tab.github.io/2021/08/09/femonitor/" title="前端异常监控平台"><img src= "" data-lazy-src="/tab.github.io/2021/08/09/femonitor/IMG_2992.jpeg" onerror="this.onerror=null;this.src='/tab.github.io/img/404.jpg'" alt="前端异常监控平台"/></a><div class="content"><a class="title" href="/tab.github.io/2021/08/09/femonitor/" title="前端异常监控平台">前端异常监控平台</a><time datetime="2021-08-09T12:25:00.000Z" title="发表于 2021-08-09 20:25:00">2021-08-09</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/tab.github.io/2021/07/08/ssr/" title="性能优化之SSR初体验"><img src= "" data-lazy-src="/tab.github.io/2021/07/08/ssr/ssr.jpg" onerror="this.onerror=null;this.src='/tab.github.io/img/404.jpg'" alt="性能优化之SSR初体验"/></a><div class="content"><a class="title" href="/tab.github.io/2021/07/08/ssr/" title="性能优化之SSR初体验">性能优化之SSR初体验</a><time datetime="2021-07-08T06:37:22.000Z" title="发表于 2021-07-08 14:37:22">2021-07-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/tab.github.io/2021/05/15/inject/" title="Vue3.0——Provide/Inject的妙用"><img src= "" data-lazy-src="/tab.github.io/2021/05/15/inject/top.jpg" onerror="this.onerror=null;this.src='/tab.github.io/img/404.jpg'" alt="Vue3.0——Provide/Inject的妙用"/></a><div class="content"><a class="title" href="/tab.github.io/2021/05/15/inject/" title="Vue3.0——Provide/Inject的妙用">Vue3.0——Provide/Inject的妙用</a><time datetime="2021-05-15T15:07:43.000Z" title="发表于 2021-05-15 23:07:43">2021-05-15</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By Tab</div><div class="footer_custom_text">Hi, welcome to my <a href="https://tabxx.github.io/tab.github.io/">blog</a>!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/tab.github.io/js/utils.js"></script><script src="/tab.github.io/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'DCF6gBtqrrJYBofXtoomsqy4-gzGzoHsz',
      appKey: 'e9JXPlIRUQ8XLONSE4dsozQA',
      placeholder: 'Please leave your footprints',
      avatar: 'monsterid',
      meta: 'nick,mail,link'.split(','),
      pageSize: '10',
      lang: 'zh-CN',
      recordIP: false,
      serverURLs: '',
      emojiCDN: '',
      emojiMaps: "",
      enableQQ: false,
      path: window.location.pathname,
      requiredFields: ["nick,mail"],
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>